package com.chiry.testokhttp;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chiry.testokhttp.okhttp.OkHttpUtil;
import com.chiry.testokhttp.utils.Result;
import okhttp3.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@SpringBootApplication
@RestController
public class TestOkhttpApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestOkhttpApplication.class, args);
    }
    @RequestMapping("/test")
    public Result<Object> testControllerMethod(){
        String s = OkHttpUtil.get("http://www.httpbin.org/get", null);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        Result<Object> res = Result.success(jsonObject.getStr("url"));
        return res;
    }
    @RequestMapping("/test2")
    public Result<Object> testHutoolHttp(){
        HttpRequest get = HttpUtil.createGet("http://www.httpbin.org/get");
        HttpResponse execute = get.execute();
        String body = execute.body();
        return Result.success(body);
    }


    //异步 通过回调函数方式处理结果。这个当方法返回后执行这个回调函数
    @RequestMapping("test3")
    public Result<Object> testOkhttpAsynchronic(){
        Request request = new Request.Builder()
                .url("http://www.httpbin.org/get")
                .build();

        Call call = new OkHttpClient().newCall(request);

// 该方法不会阻塞,通过设置回调方法来处理执行结果
        call.enqueue(new Callback() {

            // 处理异常
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());

            }

            // 处理响应
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    System.out.println(response.body().string());
                }
            }
        });
        return Result.success();

    }

}
